<template>
  <div>
   <h2 class="title-col">用户管理     <a-button @click="modalManage('add')"> 添加</a-button> </h2> 

    <a-table :dataSource="dataSource" :columns="columns" :pagination="false">

       <template #bodyCell="{ column, record }">

         <template v-if="column.key === 'action'">
              <a-button @click="modalManage('edit', record)">编辑</a-button>
              <a-button>删除</a-button>
         </template>
       </template>
    </a-table>
     <!-- show-size-changer
      v-model:page-size="pageSizeRef" -->
 <a-pagination
    v-model:current="pageObj.pageIndex"
    :total="pageObj.total"
    @change="pageChangeFun"
  >
  </a-pagination>
    <a-modal v-model:open="modalObj.open" :title="modalObj.title" @ok="handleOk" width="800px" >
        
       <a-form
          ref="formRef"
          style="height:500px;overflow: auto;"
          :model="formState"
          :rules="rules"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
        >
          <!-- 基础信息部分 -->
          <div class="form-section">
            <h3 class="section-title">基础信息</h3>
            <div class="form-row">
              <a-form-item label="用户名" name="userName">
                <a-input disabled v-model:value="formState.userName" placeholder="请输入用户名" />
              </a-form-item>
              
              <a-form-item label="密码" name="password">
                <a-input-password v-model:value="formState.password" placeholder="请输入密码" />
              </a-form-item>
            </div>
            
            <div class="form-row">
              <a-form-item label="昵称" name="nickName">
                <a-input v-model:value="formState.nickName" placeholder="请输入昵称" />
              </a-form-item>
              
              <a-form-item label="真实姓名" name="realName">
                <a-input v-model:value="formState.realName" placeholder="请输入真实姓名" />
              </a-form-item>
            </div>
          </div>
          
          <!-- 联系信息部分 -->
          <div class="form-section">
            <h3 class="section-title">联系信息</h3>
            <div class="form-row">
              <a-form-item label="手机号" name="phone">
                <a-input v-model:value="formState.phone" placeholder="请输入手机号" />
              </a-form-item>
              
              <a-form-item label="身份证号" name="identityNum">
                <a-input v-model:value="formState.identityNum" placeholder="请输入身份证号" />
              </a-form-item>
            </div>
            
            <a-form-item label="地址" name="address" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
              <a-input v-model:value="formState.address" placeholder="请输入地址" />
            </a-form-item>
          </div>
          
          <!-- 其他信息部分 -->
          <div class="form-section">
            <h3 class="section-title">其他信息</h3>
            <div class="form-row">
              <a-form-item label="角色" name="role">
                <a-select v-model:value="formState.role" placeholder="请选择角色">
                  <a-select-option value="user">用户</a-select-option>
                  <a-select-option value="expert">专家</a-select-option>
                  <a-select-option value="admin">管理员</a-select-option>
                </a-select>
              </a-form-item>
              
              <a-form-item label="头像" name="avatar">
                <!-- {{ formState.avatar }} -->

                <ImageUpload v-if="Array.isArray(formState.avatar)" :currentImages="formState.avatar" @success="uploadFileSuccess"> </ImageUpload>
               <ImageUpload v-else :currentImages="[formState.avatar]" @success="uploadFileSuccess"> </ImageUpload>
              </a-form-item>
            </div>
            
            <div class="form-row">
              <a-form-item label="积分" name="integral">
                <a-input-number v-model:value="formState.integral" :min="0" style="width: 100%" />
              </a-form-item>
              
              <a-form-item label="信用" name="credit">
                <a-input-number v-model:value="formState.credit" :min="0" style="width: 100%" />
              </a-form-item>
            </div>
          </div> 
        </a-form>
    </a-modal>
  </div>
</template>

<script  setup>
import { onMounted, reactive,ref } from 'vue'
import axiosEl from '@/utils/axiosEl'
import { message } from 'ant-design-vue'
import ImageUpload from '@/components/ImageUpload.vue';

const pageObj = ref({
  pageIndex:1,
  pageSize:10,
  total:0
})
 const formState = ref({
          userName: '',
          password: '',
          nickName: '',
          realName: '',
          phone: '',
          identityNum: '',
          address: '',
          role: '',
          integral: 0,
          credit: 0,
          avatar: ''
        });
  // 表单验证规则
        const rules = {
          userName: [
            { required: true, message: '请输入用户名', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { 
              pattern: /^[a-zA-Z][a-zA-Z0-9_]{5,17}$/, 
              message: '密码必须以字母开头，长度在6-18之间，只能包含英文字符、数字和下划线',
              trigger: 'blur'
            }
          ],
          nickName: [
            { required: true, message: '昵称不能为空', trigger: 'blur' }
          ],
          phone: [
            { 
              pattern: /^1[3|4|5|7|8][0-9]{9}$/, 
              message: '请输入正确的手机号',
              trigger: 'blur'
            }
          ],
          identityNum: [
            { 
              pattern: /^\d{15}|\d{18}$/, 
              message: '请输入15或18位有效身份证号',
              trigger: 'blur'
            }
          ],
          address: [
            { 
              min: 2, 
              max: 30, 
              message: '地址长度应在2-30个字符之间',
              trigger: 'blur'
            }
          ],
          role: [
            { 
              pattern: /^(user|expert|admin)$/, 
              message: '请选择正确的角色',
              trigger: 'change'
            }
          ]
        };
         
// 模态框
const modalObj = ref({
  open:false,
  title:'添加用户',
  kind:'add'
})
const formRef = ref(null)
// 点击确定按钮的回调函数
const handleOk =  async ()=>{
  // 提交form表单 验证表单
  await formRef.value.validate()

  if(modalObj.value.kind == 'add'){
      await  axiosEl({
        url:'/api/user/add',
        method:'post',
        data:{ ...formState.value, avatar: formState.avatar[0] }
      })
  } else {
       await  axiosEl({
        url:'/api/user/update',
        method:'post',
        data:{ ...formState.value, avatar: formState.avatar[0] }
      })
  }

  modalObj.value.open = false;
  // 更新数据列表
   getUserList();
   message.success(modalObj.value.kind =='add'? '用户添加成功！':'用户编辑成功！');
  
}

const uploadFileSuccess = (data)=>{
  console.log(data,'图片上传成功后');
  formState.avatar = data;
  
}

const pageChangeFun = (page, pageSize)=>{
    pageObj.value.pageIndex = page;
    pageObj.value.pageSize = pageSize;

    getUserList();
}
const modalManage = (kind,data)=>{

    modalObj.value  = {
      open:true,
      title:kind == 'add'? '添加用户':'编辑用户',
      kind:kind
    };

   formState.value = {...data} || {}

}
const dataSource =  ref([
          {
            key: '1',
            name: '胡彦斌',
            age: 32,
            address: '西湖区湖底公园1号',
          },
          {
            key: '2',
            name: '胡彦祖',
            age: 42,
            address: '西湖区湖底公园1号',
          },
        ])
  const columns = [
          {
            title: '用户名',
            dataIndex: 'userName',
            key: 'userName',
          },
          {
            title: '昵称',
            dataIndex: 'nickName',
            key: 'nickName',
          },
          {
            title: '住址',
            dataIndex: 'address',
            key: 'address',
          },
          {
            title: '手机号',
            dataIndex: 'phone',
            key: 'phone',
          },
           {
            title: '操作',
            key: 'action',
          },
        ]

  const getUserList =async ()=>{
    const resData = await axiosEl({
      method:'get',
      url:'/api/user/list',
      params:{
        pageNum: pageObj.value.pageIndex,
        pageSize:pageObj.value.pageSize
      }
    })
    console.log(resData,'获取接口数据');
    dataSource.value = resData.data.records;

    pageObj.value.total = resData.data.total;
    
  }
 onMounted(()=>{
    getUserList();
 }) 
</script>

<style lang='scss' scoped>
.title-col {
  display: flex;
  justify-content: space-between;
}
</style>